package org.soderiakelvy.model.dao.imp;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.soderiakelvy.model.dao.VisitaDao;
import org.soderiakelvy.model.domain.RepartoVO;
import org.soderiakelvy.model.domain.SucursalVO;
import org.soderiakelvy.model.domain.VisitaVO;
import org.soderiakelvy.model.util.HibernateUtil;

public class VisitaDaoImp implements VisitaDao, Serializable{
	private static final long serialVersionUID = 1L;

	@Override
	public void insertVisitaVO(VisitaVO visita) throws Exception {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.save(visita);
		session.getTransaction().commit();
		session.close();
	}

	@Override
	public void updateVisitaVO(VisitaVO visita) throws Exception {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.update(visita);
		session.getTransaction().commit();
		session.close();
	}

	@Override
	public void deleteVisitaVO(VisitaVO visita) throws Exception {
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.delete(visita);
		session.getTransaction().commit();
		session.close();
		
	}

	@Override
	public VisitaVO getVisitaBySucursal(SucursalVO sucursal) throws Exception{
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		Criteria criteria = session.createCriteria(VisitaVO.class);
		criteria.add(Restrictions.eq("sucursal", sucursal));
		VisitaVO vVO = (VisitaVO) criteria.uniqueResult(); 
		session.close();
		return vVO;
	}

	@Override
	public List<VisitaVO> getVisitaByReparto(RepartoVO reparto) {
		try {
			SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
			Session session = sessionFactory.openSession();
			Criteria criteria = session.createCriteria(VisitaVO.class);
			criteria.add(Restrictions.eq("reparto", reparto));
			List<VisitaVO> visitas = criteria.list(); 
			session.close();
			return visitas;
		} catch (Exception e) {
			e.printStackTrace();
			return new ArrayList<VisitaVO>();
		}
		
	}
	
}
